#include "head.h"

#include "head.h"
int getsFunc(int sockfd, const char *filename) {

    // 下面开始接收数据
    // 先判断是不是断点续传

    //train_name_t train_name;
    //bzero(&train_name, sizeof(train_name));

    printf("开始下载......\n");
    off_t offset = 0;
    if (access(filename, F_OK) == 0) {
        // 文件存在
        // 这里要告诉他文件存在了
        //train_name_t train_name;
        // 用stat获取文件大小
        struct stat st;

        stat(filename, &st);

        //train_name.offset = st.st_size;

        //train_name.offset
        offset = st.st_size;
        send(sockfd, &offset, sizeof(off_t), MSG_NOSIGNAL);
        //接受服务器消息
        int ifErrorNum;
        recvn(sockfd, &ifErrorNum, sizeof(int));
        if (ifErrorNum != 0) {
            printf("gets is error\n");
            return -1;
        }

        train_t train_file;
        int fd = open(filename, O_WRONLY|O_CREAT, 0666);

        // lseek(fd, (off_t)train_name.offset, SEEK_SET);
        
        lseek(fd, offset, SEEK_SET);

        // 对返回的fd做报错分析
        while(1){
            bzero(&train_file, sizeof(train_file));
            //printf("bzero over\n");
            recvn(sockfd, &train_file.length, sizeof(train_file.length));
            printf("下载文件大小：%d\n",train_file.length);
            if(train_file.length==0){
                printf("下载结束......\n");
                break;
            }
            // recvn(sockfd, &train_file.offset,sizeof(train_file.offset));
            recvn(sockfd, train_file.data, train_file.length);
            write(fd, train_file.data, train_file.length);
        }
    } else {
        off_t offset = 0;
        send(sockfd, &offset, sizeof(off_t), 0);
        /*int ifError;
          recv(sockfd, &ifError, sizeof(int), 0);
          if (ifError != 0) {
        // 接收一个小火车
        print_network_message(sockfd);
        return -1;
        }*/

        // 上边是报错
        // 开始传输
        // 注意open操作的第二个参数
        int ifErrorNum;
        recvn(sockfd, &ifErrorNum, sizeof(int));
        if (ifErrorNum != 0) {
            printf("gets is error\n");
            return -1;
        }
        printf("filename = %s\n", filename);
        train_t train_file;
        int fd = open(filename, O_WRONLY|O_CREAT, 0666);
        // 注意这里TRUNC是不是多余的
        //
        printf("fd is %d\n",fd);
        //
        //
        // 对返回的fd做报错分析
        while(1){
            bzero(&train_file, sizeof(train_file));
            //printf("bzero over\n");
            recvn(sockfd, &train_file.length, sizeof(train_file.length));
            printf("下载文件大小：%d\n",train_file.length);
            if(train_file.length==0){
                printf("下载结束......\n");
                break;
            }
            // recvn(sockfd, &train_file.offset,sizeof(train_file.offset));
            recvn(sockfd, train_file.data, train_file.length);
            write(fd, train_file.data, train_file.length);
        }
    }
    return 0;
}
